package com.hxf.dao.user.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.hxf.dao.BaseDaoImpl;
import com.hxf.dao.user.AdminUserDao;
import com.hxf.dto.AdminRoleDto;
import com.hxf.dto.AdminUserDto;
import com.hxf.dto.AdminUserRoleDto;
import com.hxf.dto.ReturnData;
import com.hxf.dto.RoleDto;
import com.hxf.dto.UserDto;
import com.hxf.exception.DaoLevelException;

@Repository("adminUserDao")
public class AdminUserDaoImpl extends BaseDaoImpl implements AdminUserDao {

	/**
	 * 联盟管理员信息
	 */
	@Override
	public ReturnData<AdminUserDto> findAdminUser(AdminUserDto adminUserDto, int targetPage, int pageSize)throws DaoLevelException{
		
		return super.findBy(" from AdminUserDto where 1=1 " , targetPage, pageSize);
	}
	
	/**
	 * 后台管理员登陆
	 */
	@Override
	public int loginUser(AdminUserDto userDto) throws DaoLevelException { 
		List<AdminUserDto> userList = this.findBy("from AdminUserDto where userName = '"+userDto.getUserName()+"'");
		//用户名不存在
		if (userList == null || userList.size() == 0) {
			return -1;
		} 
		
		userList = this.findBy("from AdminUserDto where userPwd = '"+userDto.getUserPwd()+"' and userName = '"+userDto.getUserName()+"'");
		//密码不存在
		if (userList == null || userList.size() == 0) {
			return -2;
		}  
		//账号审核中

		if (userList.get(0).getStatus() == 1) {
			return -3;
		}
		//审核不通过
		if (userList.get(0).getStatus() == 2) {
			return -4;
		} 
		//锁定
		if (userList.get(0).getStatus() == 3) {
			return -5;
		}
		//作废
		if (userList.get(0).getStatus() == 4) {
			return -6;
		} 
		userDto.setId(userList.get(0).getId()); 
		
		return 0;
	}
	
	public int deleteUserRoleByUserId(Integer userId) throws DaoLevelException {
		return this.executeUpdateBySql("delete from rk_admin_user_role where user_id="+userId);
	}
	
	@Override
	public List<RoleDto> findByUserRole(AdminUserDto urDto)throws DaoLevelException {
		String sql = "select distinct rr.role_id ,rr.role_name ,rr.remark,rr.status from rk_admin_user as ru, rk_admin_user_role as rur,rk_role as rr where   ru.id = rur.user_id "+ 
					 "and rur.role_id = rr.role_id  and ru.id='"+urDto.getId()+"'"; 
		List list = this.exeSQLList(sql); 
		List<RoleDto> userRoleVoList = null;
		RoleDto urVo = null;
		if (list != null && list.size() > 0) {
			userRoleVoList = new ArrayList<RoleDto>();
			for (int i = 0;i < list.size(); i++) {
				Object [] o = (Object[]) list.get(i);
				urVo = new RoleDto();
				urVo.setRoleId(null==o[0]?null:Integer.parseInt(o[0].toString()));
				urVo.setRoleName(null==o[1]?null:o[1].toString());
				urVo.setRemark(null==o[2]?null:o[2].toString());
				urVo.setStatus(null==o[3]?null:Integer.parseInt(o[3].toString())); 
				userRoleVoList.add(urVo);
			}
		}
		return userRoleVoList;
	}
}
